package com.moo2u2.android.oaktononthego.timesheet;

import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.moo2u2.android.oaktononthego.R;
import com.moo2u2.android.oaktononthego.fragment.CallbackListFragment;
import com.moo2u2.android.oaktononthego.timesheet.dao.TimesheetDbAdapter;
import com.moo2u2.android.oaktononthego.timesheet.dao.TimesheetEntryTable;
import com.moo2u2.android.oaktononthego.timesheet.dao.TimesheetTable;

public class TimesheetEntryPrompt extends AlertDialog.Builder implements
		AdapterView.OnItemSelectedListener {

	// TODO implement this whole dialog as a fragment

	private static final Map<String, Integer> dropdownDetailsMap = new HashMap<String, Integer>();

	static {
		dropdownDetailsMap.put("Non-Project Time",
				R.array.timesheet_types_non_project);
		dropdownDetailsMap.put("Leave", R.array.leave);
		dropdownDetailsMap.put("Client Billable Time", R.array.client_time);
		dropdownDetailsMap
				.put("Extra Time (Non-Billable)", R.array.client_time);
		dropdownDetailsMap.put("Weekday Overtime", R.array.client_time);
		dropdownDetailsMap.put("Weekend Overtime", R.array.client_time);
	}

	private Context ctx;

	private AlertDialog dialog; // itself

	private Spinner types;

	private Spinner subtypes;

	private EditText hours, notes;

	public TimesheetEntryPrompt(final Context ctx,
			final CallbackListFragment fragment, final Calendar currentWeek,
			final int day, final Cursor cursor) {
		super(ctx);
		this.ctx = ctx;
		final boolean newEntry = (cursor == null);

		setTitle("Add entry");
		setMessage("Add a timesheet entry");

		final long entryId = newEntry ? -1 : cursor.getLong(cursor
				.getColumnIndexOrThrow(TimesheetEntryTable.KEY_TIMESHEET));

		setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				TimesheetDbAdapter dbHelper = new TimesheetDbAdapter(ctx);
				dbHelper.open();

				Cursor timesheet = dbHelper.fetchTimesheet(currentWeek
						.getTime());
				if (timesheet.getCount() < 1) {
					Log.i(this.getClass().getSimpleName(),
							"No timesheet for this week, creating...");
					dbHelper.createTimesheet(currentWeek.getTime(), false);
					timesheet = dbHelper.fetchTimesheet(currentWeek.getTime());
				} else
					timesheet.moveToFirst();
				long timesheetId = timesheet.getLong(timesheet
						.getColumnIndexOrThrow(TimesheetTable.KEY_ROWID));
				timesheet.deactivate();

				String selectedTypeTxt = ctx.getResources().getStringArray(
						R.array.timesheet_types)[types
						.getSelectedItemPosition()];
				String selectedSubtypeTxt = subtypes.getSelectedItem()
						.toString();
				String notesTxt = notes.getText().toString();
				Integer hoursNum = -1;
				try {
					hoursNum = Integer.parseInt(hours.getEditableText()
							.toString());
				} catch (NumberFormatException e) {
					Log.e(this.getClass().getSimpleName(), "Invalid hours");
				}
				if (hoursNum < 1) {
					Toast.makeText(ctx, "Invalid hours", Toast.LENGTH_SHORT)
							.show();
					dbHelper.close();
					return;
				}
				if (newEntry)
					dbHelper.createTimesheetEntry(timesheetId, day,
							selectedTypeTxt, selectedSubtypeTxt, hoursNum,
							notesTxt);
				else
					dbHelper.updateTimesheetEntry(entryId, timesheetId, day,
							selectedTypeTxt, selectedSubtypeTxt, hoursNum,
							notesTxt);

				dbHelper.close();

				Log.i(this.getClass().getSimpleName(), "Added entry day " + day);
				fragment.getLoaderManager().restartLoader(0, null, fragment);
			}
		});

		setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Canceled.
			}
		});

		hours = new EditText(ctx);
		hours.setInputType(InputType.TYPE_CLASS_NUMBER);
		// hours.setText("8");
		if (cursor != null)
			hours.setText(String.valueOf(cursor.getInt(cursor
					.getColumnIndexOrThrow(TimesheetEntryTable.KEY_HOURS))));

		notes = new EditText(ctx);
		if (cursor != null)
			notes.setText(String.valueOf(cursor.getInt(cursor
					.getColumnIndexOrThrow(TimesheetEntryTable.KEY_NOTES))));

		types = new Spinner(ctx);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				ctx, R.array.timesheet_types,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		types.setAdapter(adapter);
		types.setOnItemSelectedListener(this);
		if (cursor != null) {
			List<CharSequence> timesheetTypes = Arrays.asList(ctx
					.getResources().getTextArray(R.array.timesheet_types));
			String setType = cursor.getString(cursor
					.getColumnIndexOrThrow(TimesheetEntryTable.KEY_TYPE));
			if (timesheetTypes.contains(setType))
				types.setSelection(timesheetTypes.indexOf(setType));
		}

		subtypes = new Spinner(ctx);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		subtypes.setAdapter(ArrayAdapter.createFromResource(ctx,
				R.array.timesheet_types_none,
				android.R.layout.simple_spinner_item));
		subtypes.setOnItemSelectedListener(this);
		subtypes.setVisibility(View.GONE);
		if (cursor != null) {
			List<CharSequence> timesheetSubtypes = Arrays.asList(ctx
					.getResources().getTextArray(R.array.timesheet_types_none));
			String setSubtype = cursor.getString(cursor
					.getColumnIndexOrThrow(TimesheetEntryTable.KEY_SUBTYPE));
			if (timesheetSubtypes.contains(setSubtype))
				subtypes.setSelection(timesheetSubtypes.indexOf(setSubtype));
		}

		LinearLayout alertLayout = new LinearLayout(ctx), hoursLayout = new LinearLayout(
				ctx);
		hoursLayout.setOrientation(LinearLayout.HORIZONTAL);
		TextView hoursTxt = new TextView(ctx);
		hoursTxt.setText("Hours: ");
		hoursLayout.addView(hoursTxt);
		hoursLayout.addView(hours);
		alertLayout.setOrientation(LinearLayout.VERTICAL);
		alertLayout.addView(types);
		alertLayout.addView(subtypes);
		alertLayout.addView(hoursLayout);
		alertLayout.addView(notes);
		setView(alertLayout);

		if (cursor != null) {
			cursor.close();
			cursor.deactivate();
		}
	}

	/** {@inheritDoc} */
	@Override
	public void onItemSelected(AdapterView<?> parent, View v, int position,
			long id) {
		String selected = ctx.getResources().getStringArray(
				R.array.timesheet_types)[types.getSelectedItemPosition()];
		Integer stringArray = dropdownDetailsMap.get(selected);
		if (stringArray != null) {
			subtypes.setAdapter(ArrayAdapter.createFromResource(ctx,
					stringArray, android.R.layout.simple_spinner_item));
			setEnabled(true);
		} else {
			setEnabled(false);
		}
	}

	/** {@inheritDoc} */
	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		Log.i(this.getClass().getSimpleName(), "Nothing selected");
	}

	private void setEnabled(boolean enabled) {
		if (enabled) {
			subtypes.setVisibility(View.VISIBLE);
		} else {
			subtypes.setVisibility(View.GONE);
		}
		hours.setEnabled(enabled);
		notes.setEnabled(enabled);
		// this is an ugly hack
		if (dialog != null) {
			if (dialog.getButton(AlertDialog.BUTTON_POSITIVE) != null)
				dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(
						enabled);
		}
	}

	public AlertDialog getDialog() {
		return dialog;
	}

	public void setDialog(AlertDialog dialog) {
		this.dialog = dialog;
	}

}
